﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.IdentityModel.Selectors;
using System.ServiceModel.Description;

namespace Service
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8003/calc");

            using (ServiceHost host = new ServiceHost(typeof(CalcService), baseAddress))
            {
                BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Message);
                binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

                host.AddServiceEndpoint(typeof(ICalc), new BasicHttpBinding(), "");

                ServiceMetadataBehavior smb = (ServiceMetadataBehavior)
                    host.Description.Behaviors.Find<ServiceMetadataBehavior>();
                if (smb == null)
                {
                    smb = new ServiceMetadataBehavior();
                    smb.HttpGetEnabled = true;
                    host.Description.Behaviors.Add(smb);
                }

                host.Open();

                Console.WriteLine("Service is opened!");

                Console.ReadLine();
            }

            Console.ReadLine();
        }
    }

    [ServiceContract(Namespace = "http://vanglen")]
    public interface ICalc
    {
        [OperationContract]
        double Add(double n1, double n2);
    }

    [ServiceBehavior]
    public class CalcService : ICalc
    {
        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }
    }


    public class CustomUserNameValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (null == userName || null == password)
            {
                throw new ArgumentNullException();
            }

            if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset"))
            {
                // This throws an informative fault to the client.
                throw new FaultException("Unknown Username or Incorrect Password");
                // When you do not want to throw an infomative fault to the client,
                // throw the following exception.
                // throw new SecurityTokenException("Unknown Username or Incorrect Password");
            }

        }
    }
}
